#!/usr/bin/python

import _mysql
import json

def getDBCon(db="ha",host='localhost'):
    if db == "ha": return _mysql.connect(host=host,user="ha",passwd="homeauto",db="home_automation")
    if db == "fi": return _mysql.connect(host=host,user="finance",passwd="finance",db="finance")

def getResult(query, db):
    db.query(query)
    r=db.use_result()
    return r

def getOneResult(query, db):
    db.query(query)
    r=db.use_result()
    return r.fetch_row()

def getSensor(name,type, db):
    tid=getOneResult("SELECT id from sensor_types WHERE description = '"+type+"'",db)
    if len(tid)==0:
        db.query("INSERT INTO sensor_types VALUES ( null , '"+type+"' )")
        tid=getOneResult("SELECT id from sensor_types WHERE description = '"+type+"'",db)
    id=getOneResult("SELECT id from sensors WHERE description = '"+name+"' and type = "+tid[0][0],db)
    if len(id)==0:
        db.query("INSERT INTO sensors VALUES ( null, '"+tid[0][0]+"' , '"+name+"' )")
        id=getOneResult("SELECT id from sensors WHERE description = '"+name+"' and type = "+tid[0][0],db)
    return id[0][0]

def returnTimeSeries(db, data, table, filter, date='date'):
    getResult("SELECT "+data+", "+date+" from "+table+" WHERE "+filter)
    row=r.fetch_row()
    result=[]
    while( len(row )>0):
        entry={ 'x': float(row[0][0]), 'y': float(row[0][1]) };
        result.append(entry)
        row=r.fetch_row()
    return json.dumps(result)

